//index.js
//获取应用实例
import stationData from './data.js'

const app = getApp()

const date = new Date()
const year = date.getFullYear()
const month = date.getMonth()+1
const day = date.getDate()

Page({
  data: {
    year:year,
    month:month,
    day:day,
    nextyear:year+1,
    motto: 'Powered by @小牛皮抢票',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    items: [
      { value: '二等座' },
      { value: '一等座' },
      { value: '无座' },
      { value: '硬卧' },
      { value: '软卧' },
      { value: '硬座' },
      { value: '软座' },
      { value: '动卧' },
      { value: '商务座' },
      { value: '特等座' },
      { value: '高级软卧' },
      { value: '高级动卧' },
    ],
    formData:{
      userInfos: [
        { cardNumber: '', ifocus: false, ierr: false, userName: '', nfocus: false , nerr: false}
      ],
      fromStationText: null,
      toStationText: '',
      spareFromStationText: '',
      spareToStationText: '',
      trainDate: '',
      /*
      spareTrainDate: '',
      backTrainDate: '',
      spaceBackTrainDate: '',
      */
      backTrainDate: '',
      remark: null,
      trainNumber: null,
      spareTrainNumber: '',
      //seatRemark: null,
      phone: null,
      code:null,
      systemid:null,
      sessionId:null
    },
    focusData:{seat:true},
    errData:{}
  },
  bindDateChange: function (e) {
    this.setData({
      'formData.trainDate': e.detail.value
    })
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../order/order'
    })
  },
  onLoad: function () {
    wx.setStorageSync('reload', true)
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  getUserInfo: function(e) {
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  makePhoneCall:function(e){
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.phone,
    })
  },
  deleteThis: function(e) {
    // 删除当前一条
    this.data.formData.userInfos.splice(e.target.dataset.idx,1)
    this.setData({
      'formData.userInfos': this.data.formData.userInfos
    })
  },
  addOne: function(e) {
    // 身份，号码在数组后加一条
    this.data.formData.userInfos = this.data.formData.userInfos.concat([{ cardNumber: '', userName: '' }])
    this.setData({
      'formData.userInfos': this.data.formData.userInfos
    })
  },

  //******** 输入取值部分开始 ******//
  checkboxChange: function (e) {
    // 坐次多选卡
    if (!e.detail.value.length){
      this.data.focusData.seat = true;
    } else {
      this.data.focusData.seat = false;
    }
    this.setData({
      'formData.seat': e.detail.value.join(':'),
      focusData: this.data.focusData
    })    
  },
  bindIdcard: function (e) {
    // 身份证
    this.data.formData.userInfos[e.target.dataset.id].cardNumber = e.detail.value
    this.reFocus(0)
    //this.data.formData.userInfos[e.target.dataset.id].ifocus = true
    this.setData({
      'formData.userInfos': this.data.formData.userInfos
    })
    //this.reFocus(0)
    
  },
  bindName: function (e) {
    // 姓名
    this.data.formData.userInfos[e.target.dataset.id].userName = e.detail.value
    this.reFocus(0)
    //this.data.formData.userInfos[e.target.dataset.id].nfocus = true
    this.setData({
      'formData.userInfos': this.data.formData.userInfos
    })
    
    //this.reFocus(0)
  },
  bindInput: function (e) {
    this.data.formData[e.target.dataset.formid] = e.detail.value
    
    this.reFocus(0)
    //this.data.focusData[e.target.dataset.formid] = true
    
    this.setData({
      'formData': this.data.formData
    })
    
  },
  bindIdFocus: function (e) {
    this.data.formData.userInfos[e.target.dataset.id].cardNumber = e.detail.value
    this.reFocus(0)
    this.data.formData.userInfos[e.target.dataset.id].ifocus = true
    this.setData({
      'formData.userInfos': this.data.formData.userInfos
    })
    
  },
  bindNameFocus: function (e) {
    this.data.formData.userInfos[e.target.dataset.id].userName = e.detail.value
    this.reFocus(0)
    this.data.formData.userInfos[e.target.dataset.id].nfocus = true
    this.setData({
      'formData.userInfos': this.data.formData.userInfos
    })
    
  },
  bindFocus: function (e) {
    this.data.formData[e.target.dataset.formid] = e.detail.value
    this.reFocus(0)
    this.data.focusData[e.target.dataset.formid] = true
    this.setData({
      'formData': this.data.formData
    })
  },
  //******** 输入取值部分结束 ******//
  submitForm: function (e) {
    if (!this.validateForm()) {
        return false
    }

    this.data.formData.code = app.globalData.inData.code
    this.data.formData.systemid = app.globalData.inData.systemid
    this.data.formData.sessionId = wx.getStorageSync('sessionid')   

    wx.request({
      url: '####',
      data: this.data.formData,
      method: 'POST',
      success: function (res) {
        console.log(JSON.stringify(res))
        if (res.data.list){
          // 所有下单列表
          wx.setStorageSync('orders', res.list)
          wx.setStorageSync('reload', false)
          wx.navigateTo({
            url: '../order/order'
          })
        }
      }
    })
  },
  resetForm: function (e) {
    this.setData({
      formData:{
        userInfos:[{userName:null,cardName:null}]
      }
    })
  },
  validateForm: function () {
    var formData = this.data.formData    
    this.reFocus(1)
    var cardNumberT
    var userNameT
    var first = true
    var retflag = true

    // 验证火车站点
    var pinyin = ''
    var fromStationText = formData.fromStationText == null ? null : formData.fromStationText.replace(/^\s+|\s+$/g, "")
    if (fromStationText == null || !(pinyin = this.checkStation(fromStationText))) {
      retflag = false
      if (first) {
        this.data.focusData.fromStationText = true
        first = false
      }
      this.data.errData.fromStationText = true
    } else {
      this.data.formData.fromStationPinyin = pinyin
    }

    var toStationText = formData.toStationText == null ? null : formData.toStationText.replace(/^\s+|\s+$/g, "")
    if (toStationText == null || !(pinyin = this.checkStation(toStationText)) || fromStationText == toStationText) {
      retflag = false
      if (first) {
        this.data.focusData.toStationText = true
        first = false
      }
      this.data.errData.toStationText = true
    } else {
      this.data.formData.toStationPinyin = pinyin
    }

    var spareFromStationText = formData.spareFromStationText == null ? null : formData.spareFromStationText.replace(/^\s+|\s+$/g, "")
    if (spareFromStationText) {
      if (!(pinyin = this.checkStation(spareFromStationText))) {
        retflag = false
        if (first) {
          this.data.focusData.spareFromStationText = true
          first = false
        }
        this.data.errData.spareFromStationText = true
      } else {
        this.data.formData.spareFromStationPinyin = pinyin
      }
    }

    var spareToStationText = formData.spareToStationText == null ? null : formData.spareToStationText.replace(/^\s+|\s+$/g, "")
    if (spareToStationText) {
      if (!(pinyin = this.checkStation(spareToStationText))) {
        retflag = true
        if (first) {
          this.data.focusData.spareToStationText = true
          first = false
        }
        this.data.errData.spareToStationText = true
      } else {
        this.data.formData.spareToStationPinyin = pinyin
      }
    }

    // 验证日期
    if (!formData.trainDate){
      retflag = false
      if (first) {
        this.data.focusData.trainDate = true
        first = false
      }
      this.data.errData.trainDate = true
    }

    // 验证手机
    if (!/^1[3|4|5|7|8][0-9]\d{8}$/.test(formData.phone)) {
      retflag = false
      if (first) {
        this.data.focusData.phone = true
        first = false
      }
      this.data.errData.phone = true
    }

    this.checkUserData()

    var userinfos = this.data.formData.userInfos
    var len = userinfos.length
    
    for (var i = 0; i < len; i++) {
      cardNumberT = userinfos[i].cardNumber
      userNameT = userinfos[i].userName
      // 验证身份证
      if (!cardNumberT || (!/^\d{17}(\d|x)$/i.test(cardNumberT) && !/^\d{15}$/i.test(cardNumberT))) {
        retflag = false
        if (first) {
          this.data.formData.userInfos[i].ifocus = true
          first = false
        }
        this.data.formData.userInfos[i].ierr = true
      }

      if (!userNameT.replace(/^\s+|\s+$/g, "")) {
        retflag = false
        if (first) {
          this.data.formData.userInfos[i].nfocus = true
          first = false
        }
        this.data.formData.userInfos[i].nerr = true
      }
    }

    // 验证坐席要求

    var seat = formData.seat
    console.log(seat)
    if(!seat){
      retflag = false
      this.data.focusData.seat = true
    }

    // 验证账号密码
    var username = formData.username == null ? null : formData.username.replace(/^\s+|\s+$/g, "")
    var password = formData.password == null ? null : formData.password.replace(/^\s+|\s+$/g, "")
    if ((!username || !password) && username != password) {
      retflag = false
      if (first) {
        if (!username) {
          this.data.focusData.username = true
        } else {
          this.data.focusData.password = true
        }
        first = false
      }

      if (!username) {
        this.data.errData.username = true
      } else {
        this.data.errData.password = true
      }
    }

    this.setData({
      formData: this.data.formData,
      focusData: this.data.focusData,
      errData: this.data.errData
    })
    return retflag
  },
  checkUserData: function(){
    // 去身份号和姓名同时为空的行 除了第一行
    var userinfos = this.data.formData.userInfos

    var len = userinfos.length
    var cardNumberT
    var userNameT
    for (var i=0; i < len; i++) {
      cardNumberT = userinfos[i].cardNumber
      userNameT = userinfos[i].userName
      if (!cardNumberT.replace(/^\s+|\s+$/g, "") && !userNameT.replace(/^\s+|\s+$/g, "") && i > 0){
        this.data.formData.userInfos.splice(i,1)
      }
    }  
  },
  checkStation: function (station) {
    var stData = stationData.stations

    var slen = stData.length
    var k = 0
    var flag = false // 标记匹配到了
    for(var i=0; i < slen; i++){
      if (stData[i].station == station){
        flag = true
        k = i
        break
      }
    }
    if(flag){
      return stData[k].pinyin
    }    
    return false
  },
  reFocus: function (mode) {
    this.data.focusData = {}
    if (mode) {
      this.data.errData = {}
      this.data.formData.userInfos = this.data.formData.userInfos.map(
        function (x) {
          return { cardNumber: x.cardNumber, userName: x.userName, ifocus: false, nfocus: false, ierr: false, nerr: false }
        }
      )
    } else {
      this.data.formData.userInfos = this.data.formData.userInfos.map(
        function (x) {
          return { cardNumber: x.cardNumber, userName: x.userName, ifocus: false, nfocus: false, ierr: x.ierr, nerr: x.nerr }
        }
      )
    }
  }
})
